import json
import os

import cv2
import requests
from django.shortcuts import render

# Create your views here.
from rest_framework import exceptions
from rest_framework.views import APIView

from rest_framework.response import Response

from shareAPI import models
from shareAPI2020.settings import MEDIA_ROOT
from .utils.serializers import shareSerializers


class APIResponse(Response):

    def __init__(self, data=0, msg='success', code=200, http_status=None, headers=None, exception=False, **kwargs):
        # 将外界传入的数据状态码，状态信息以及其他所有额外储存在kwargs中的信息，都格式化成data信息
        data = {
            'code': code,  # 前端用来判断的状态码
            'data': data,  # 数据状态码
            'msg': msg  # 解释内容
        }
        if kwargs:
            data.update(kwargs)
        super().__init__(data=data, status=http_status, headers=headers, exception=exception)


class Account(APIView):
    authentication_classes = []

    def get(self, request, *args, **kwargs):
        print(type(request.data))
        return Response('禁止访问123')

    # 用post查，用put更新
    def post(self, request, *args, **kwargs):

        try:
            if isinstance(request.data, list):
                return Response('错误的格式')
            pk = kwargs.get('pk')
            if pk:  # 单查
                # 0的话返回状态码是1，类型是pk的默认数据
                one_queryset = models.Score.objects.filter(statues=1, score_type__typeid=pk).all()
                seralizer = shareSerializers.B_Score_serializers(instance=one_queryset, many=True)
                return APIResponse(seralizer.data)
            else:  # 群查
                if pk == 0:  # 0的话,什么也不给返回
                    return APIResponse()
                else:
                    gonggao_querySet = models.IndexInfo.objects.first()
                    print(type(gonggao_querySet))
                    print(gonggao_querySet.GongGao)

                    print('没有带参数，返回固定写死的类型')
                    one_queryset = models.Score.objects.filter(statues=1, ifShowIndex=1).all()  # 显示上架&允许首页的内容
                    seralizer = shareSerializers.B_Score_serializers(instance=one_queryset, many=True)

                    return APIResponse(seralizer.data,gonggao = gonggao_querySet.GongGao)
        except Exception as e:
            print(e)
            return APIResponse(0, msg='数据查询错误')

    # 修改用put更新，必须用json方式提交  # 单增json  #批量多增[json,json]
    """【访问方法】[{"fenxiangid": 50, "word": "5"}, {"fenxiangid": 51, "word": "22225"}]"""
    def put(self, request, *args, **kwargs):
        #做一个简单验证
        hahaha = request.data.get('hahaha')
        if not hahaha or hahaha != 2020:
            return APIResponse(0,'hahaha')

        if not isinstance(request.data, list):
            queryset = models.Score.objects.filter(fenxiangid=request.data.get('fenxiangid')).first()
            if not queryset:
                return APIResponse(0, msg='fenxiangid不存在')
            serializer = shareSerializers.B_Score_serializers(queryset,
                                                              data=request.data)  # 不带实例instance是create，序列化类不能是多个序列化嵌套类，有外键关系的可以通用
            serializer.is_valid(raise_exception=True)  # 如果校验失败，会直接抛异常，返回给前台
            obj = serializer.save()  # 返回一个数据库对象实例
            return APIResponse(result=serializer.data, msg=f"分享id：[{obj.fenxiangid}]修改成功")
        elif isinstance(request.data, list):# 群改
            try:
                pks = []
                for dic in request.data:
                    pks.append(dic.get('fenxiangid'))
                data = request.data
            except:
                return APIResponse(1, msg=f"群改动数据有误")
            querySet_List = []
            updata_Data_List = []

            for index, pk in enumerate(pks):              # 将提交的list中不存在的主键item剔除
                scoreOBJ = models.Score.objects.filter(pk=pk).first()
                if scoreOBJ:
                    querySet_List.append(scoreOBJ)
                    updata_Data_List.append(data[index])
                    print('querySet_List', querySet_List)
                    print('updata_Data_List', updata_Data_List)
                else:
                    print("扔掉垃圾信息")
            # 时空穿梭
            score_ser = shareSerializers.B_Score_serializers_NoDepth(instance=querySet_List,
                                                                     data=updata_Data_List, many=True, partial=True)
            if score_ser.is_valid():
                result_obj_List = score_ser.save()
                return APIResponse(
                    results=shareSerializers.B_Score_serializers_NoDepth(result_obj_List, many=True).data)
            else:
                return APIResponse(1, msg=f"更新失败")
        else:
            return APIResponse(1, msg=f"批量修改格式提交错误，请用json或者列表来操作")

    # 增加
    # def put(self, request, *args, **kwargs):
    #
    #     """要使用可写嵌套序列化，您需要在序列化程序类上声明嵌套字段，并显式编写create（）和/或update（）方法。 """
    #     print(request.data)  #用json格式提交会得到<class 'dict'>格式
    #     if not isinstance(request.data, list):
    #         # 单增
    #         print('单条更新,需要一个查询实例queryset作为instance，用来给序列化做内容定位，data是用来修改字段的')
    #         instance = models.Score.objects.filter(ifShowIndex=1)
    #         serializer = shareSerializers.B_Score_serializers_NoDepth(data=request.data) #不带实例instance是create
    #         serializer.is_valid(raise_exception=True)  # 如果校验失败，会直接抛异常，返回给前台
    #         print(serializer.validated_data)
    #         print(serializer.errors)
    #         # print(repr(serializer))
    #         obj = serializer.save()  # 返回一个数据库对象实例
    #         # print(obj)
    #
    #         return APIResponse(result=serializer.data)
    #     else:
    #         # 群增,请求
    # [{"fenxiangn23ame": "555", "score_type": "3"}, {"fenxiangn23ame": "555", "score_type": "3"}]
    #         print('多条更新')
    #         serializer = shareSerializers.B_Score_serializers_NoDepth(data=request.data, many=True)
    #         serializer.is_valid(raise_exception=True)  # 如果校验失败，会直接抛异常，返回给前台
    #         objs = serializer.save()
    #         # 为什么要将新增的对象重新序列化给前台：序列化与反序列化数据不对等
    #         return APIResponse(result=shareSerializers.B_Score_serializers(objs, many=True).data)


class Types(APIView):
    authentication_classes = []

    def get(self, request, *args, **kwargs):
        all_queryset = models.Type.objects.filter(type_statues=1).all()

        seralizer = shareSerializers.B_Type_serializers(instance=all_queryset, many=True)

        # data = {
        #     'code':200,
        #     'data': {
        #         'fxList': [
        #             {
        #                 "fenxiangid": 1,
        #                 "fenxiangIMG": "../../static/itemsPNG/wp.png",
        #                 "fenxiangname": "百度云盘",
        #                 "fenxiangusername": "WOSHIYONGHUMING",
        #                 "fenxiangpassword": "666666",
        #                 "fenxiangdata": "2020-03-20 22:08:25",
        #                 "word": "12323用",
        #                 "redword": "2可以用",
        #             },
        #         ]
        #     }
        # }
        # print(data)
        return APIResponse(seralizer.data)

    def post(self, request, *args, **kwargs):
        all_queryset = models.Type.objects.filter(type_statues=1).all()

        seralizer = shareSerializers.B_Type_serializers(instance=all_queryset, many=True)

        # data = {
        #     'code':200,
        #     'data': {
        #         'fxList': [
        #             {
        #                 "fenxiangid": 1,
        #                 "fenxiangIMG": "../../static/itemsPNG/wp.png",
        #                 "fenxiangname": "百度云盘",
        #                 "fenxiangusername": "WOSHIYONGHUMING",
        #                 "fenxiangpassword": "666666",
        #                 "fenxiangdata": "2020-03-20 22:08:25",
        #                 "word": "12323用",
        #                 "redword": "2可以用",
        #             },
        #         ]
        #     }
        # }
        # print(data)
        return APIResponse(seralizer.data)


class AddInfo(APIView):  #本接口post专门为增加内容而准备(增加账号表数据或者是修改)
    authentication_classes = []

    def get(self, request, *args, **kwargs):
        print(type(request.data))
        return Response('禁止访问')


    # 修改用put更新，必须用json方式提交  # 单增json  #批量多增[json,json]
    """【访问方法】[{"fenxiangid": 50, "word": "5"}, {"fenxiangid": 51, "word": "22225"}]"""
    def post(self, request, *args, **kwargs):
        #做一个简单验证
        hahaha = request.data.get('hahaha')
        if not hahaha or hahaha != 2020:
            return APIResponse(0,'hahaha')

        if not isinstance(request.data, list):
            queryset = models.Score.objects.filter(fenxiangid=request.data.get('fenxiangid')).first()
            if not queryset:  #如果没有获得到id，就是新增模式
                serializer = shareSerializers.B_Score_serializers_NoDepth(data=request.data)  # 不带实例instance是create，序列化类不能是多个序列化嵌套类，有外键关系的可以通用
                # return APIResponse(0, msg='fenxiangid不存在，设置，是创建新的')
            else:#如果获得到id，就是是修改模式
                serializer = shareSerializers.B_Score_serializers(queryset,
                                                              data=request.data)  # 不带实例instance是create，序列化类不能是多个序列化嵌套类，有外键关系的可以通用
            serializer.is_valid(raise_exception=True)  # 如果校验失败，会直接抛异常，返回给前台
            obj = serializer.save()  # 返回一个数据库对象实例
            return APIResponse(result=serializer.data, msg=f"分享id：[{obj.fenxiangid}]修改成功")
        elif isinstance(request.data, list):# 群改
            try:
                pks = []
                for dic in request.data:
                    pks.append(dic.get('fenxiangid'))
                data = request.data
            except:
                return APIResponse(1, msg=f"群改动数据有误")
            querySet_List = []
            updata_Data_List = []

            for index, pk in enumerate(pks):              # 将提交的list中不存在的主键item剔除
                scoreOBJ = models.Score.objects.filter(pk=pk).first()
                if scoreOBJ:
                    querySet_List.append(scoreOBJ)
                    updata_Data_List.append(data[index])
                    print('querySet_List', querySet_List)
                    print('updata_Data_List', updata_Data_List)
                else:
                    print("扔掉垃圾信息")
            # 时空穿梭
            score_ser = shareSerializers.B_Score_serializers_NoDepth(instance=querySet_List,
                                                                     data=updata_Data_List, many=True, partial=True)
            if score_ser.is_valid():
                result_obj_List = score_ser.save()
                return APIResponse(
                    results=shareSerializers.B_Score_serializers_NoDepth(result_obj_List, many=True).data)
            else:
                return APIResponse(1, msg=f"更新失败")
        else:
            return APIResponse(1, msg=f"批量修改格式提交错误，请用json或者列表来操作")


class AddClickNum(APIView):  #本接口put专门为统计资源内容而准备(增加账号表数据或者是修改)
    authentication_classes = []

    def get(self, request, *args, **kwargs):
        print(type(request.data))
        return Response('禁止访问')


    # 修改用put更新，必须用json方式提交  # 单增json  #批量多增[json,json]
    """【访问方法】格式 {"fenxiangid": 1,"hahaha":2020}"""
    def put(self, request, *args, **kwargs):
        #做一个简单验证
        hahaha = request.data.get('hahaha')
        if not hahaha or hahaha != 2020:
            return APIResponse(0,'hahaha')

        if not isinstance(request.data, list):
            queryset = models.Score.objects.filter(fenxiangid=request.data.get('fenxiangid')).first()
            if not queryset:  #如果没有获得到id，不统计
                return APIResponse(0, msg='fenxiangid不存在')
            else:#如果获得到id，该数据值增加1
                queryset.clickNum = queryset.clickNum +1
                queryset.save()  # 统计数量增加1
                return APIResponse(1, msg=f"分享id：[{queryset.fenxiangid}]统计数量目前为{queryset.clickNum}")
        elif isinstance(request.data, list):# 群改
            return APIResponse(1, msg=f"AddClickNum函数次数数据格式出错，不能是LIST")
        else:
            return APIResponse(1, msg=f"AddClickNum函数次数数据格式出错")


class QingHuiButton(APIView):  #本接口put专门为获取清灰工具的按钮内容设置
    authentication_classes = []
    def get(self, request, *args, **kwargs):
        querySet = models.QingHuiType.objects.all().first()

        seralizer = shareSerializers.B_QingHuiType_serializers(instance=querySet, many=False)
        return APIResponse(seralizer.data)

class cao(APIView):  #本接口put专门为获取清灰工具的按钮内容设置
    authentication_classes = []
    def get(self, request, *args, **kwargs):
        querySet = models.RandomUserInfo.objects.all()
        for item in querySet:
            goodQuery = models.RandomUserInfo.objects.filter(userName=item.userName).first()

            abc = str(goodQuery.user_img)
            if 'https://abc-1253820276.cos.ap-chengdu.myqcloud.com/' in abc:
                print(goodQuery.user_img)
                abc = abc.replace('https://abc-1253820276.cos.ap-chengdu.myqcloud.com/','')
                goodQuery.user_img = abc
                goodQuery.save()
            if 'file' in abc:
                print(goodQuery.user_img)
                abc = abc.replace('file','scoreimgs/file')
                goodQuery.user_img = abc
                goodQuery.save()

        querySet = models.Type.objects.all()
        for item in querySet:
            goodQuery = models.Type.objects.filter(typeid=item.typeid).first()

            abc = str(goodQuery.typeIMG)
            if 'https://abc-1253820276.cos.ap-chengdu.myqcloud.com/' in abc:
                print(goodQuery.typeIMG)
                abc = abc.replace('https://abc-1253820276.cos.ap-chengdu.myqcloud.com/', '')
                goodQuery.typeIMG = abc
                goodQuery.save()
            if 'file' in abc:
                print(goodQuery.typeIMG)
                abc = abc.replace('file','scoreimgs/file')
                goodQuery.typeIMG = abc
                goodQuery.save()

        querySet = models.Score.objects.all()
        for item in querySet:
            goodQuery = models.Score.objects.filter(fenxiangid=item.fenxiangid).first()

            abc = str(goodQuery.fenxiangIMG)
            if 'https://abc-1253820276.cos.ap-chengdu.myqcloud.com/' in abc:
                print(goodQuery.fenxiangIMG)
                abc = abc.replace('https://abc-1253820276.cos.ap-chengdu.myqcloud.com/', '')
                goodQuery.fenxiangIMG = abc
                goodQuery.save()
            if 'file' in abc:
                print(goodQuery.fenxiangIMG)
                abc = abc.replace('file','scoreimgs/file')
                goodQuery.fenxiangIMG = abc
                goodQuery.save()

        return APIResponse('')


class Question(APIView):  #本接口get是接受问题的api，post是提交问题答案的api
    authentication_classes = []
    def get(self, request, *args, **kwargs):
        id = kwargs.get('id')
        if id:
            print('单查，查询某个题目和所有的问题')
            querySet = models.QItem.objects.filter(qItem_questions__id=id).all()

            querySearlizer = shareSerializers.B_Questions_serializers_Item(instance=querySet, many=True)
            return APIResponse(querySearlizer.data)
        else:
            # 返回列表
            querySet = models.Questions.objects.all()
            querySearlizer = shareSerializers.B_Questions_serializers(instance=querySet,many=True)
            print('群查,返回所有问题list列表')
        return APIResponse(querySearlizer.data)

    def post(self, request, *args, **kwargs):

        data = dict()
        data['id'] = request.data.get('id')  # 获取POST方法传来的值
        data['userId'] = request.data.get('userId')  # 获取POST方法传来的值
        data['token'] = request.data.get('token')  # 获取POST方法传来的值
        data['questionId'] = request.data.get('questionId')  # 获取POST方法传来的值
        data['resultA'] = request.data.get('resultA')  # 获取POST方法传来的值
        data['resultB'] = request.data.get('resultB')  # 获取POST方法传来的值
        data['resultC'] = request.data.get('resultC')  # 获取POST方法传来的值
        if not data['id']:
            return APIResponse({'result':'没有传值'})

        querySet = models.Questions.objects.filter(id=data['id']).first()
        print(data)
        # 7种答案
        if (int(data['resultA']) > int(data['resultB'])) and int(data['resultA']) > int(data['resultC']):
            print("A优")
            return APIResponse({'result':querySet.key1})

        elif (int(data['resultB']) > int(data['resultA'])) and int(data['resultB']) > int(data['resultC']):
            print("B优")
            return APIResponse({'result':querySet.key2})

        elif (int(data['resultC']) > int(data['resultA'])) and int(data['resultC']) > int(data['resultB']):
            print("C优")
            return APIResponse({'result':querySet.key3})

        elif (int(data['resultA']) == int(data['resultB'])) and int(data['resultA']) > int(data['resultC']):
            print("AB优")
            return APIResponse({'result':querySet.key4})

        elif (int(data['resultA']) == int(data['resultC'])) and int(data['resultA']) > int(data['resultB']):
            print("AC优")
            return APIResponse({'result':querySet.key5})

        elif (int(data['resultB']) == int(data['resultC'])) and int(data['resultA']) < int(data['resultB']):
            print("BC优")
            return APIResponse({'result':querySet.key6})

        else:
            print("均衡答案")
            return APIResponse({'result':querySet.key7})



class PopUserInfo(APIView):  #本接口put专门为获取清灰工具的按钮内容设置
    authentication_classes = []
    def get(self, request, *args, **kwargs):
        #获取用户名和img
        querySet = models.RandomUserInfo.objects.order_by('?').first()

        seralizer = shareSerializers.B_RandomUserInfo_serializers(instance=querySet, many=False)
        return APIResponse(seralizer.data)

class shareApiAdmin(APIView):  #本接口put专门为获取清灰工具的按钮内容设置
    authentication_classes = []
    def get(self, request, *args, **kwargs):
        #获取用户名和img

        return render(request,'light/index.html')
class lyear_main(APIView):  #本接口put专门为获取清灰工具的按钮内容设置
    authentication_classes = []
    def get(self, request, *args, **kwargs):
        #获取用户名和img

        return render(request,'light/lyear_main.html')

class cutimg(APIView):  #本接口接受上传的图片，进行裁剪后返回b64编码图片
    authentication_classes = []
    def get(self, request, *args, **kwargs):
        #获取用户名和img

        return APIResponse(0, msg='使用post提交')
    def post(self,request,*args, **kwargs):
        data = dict()
        data['url'] = request.data.get('url')  # 获取POST方法传来的值
        print(request.data)
        if not data['url']:
            return APIResponse(data={'result': '没有传值URL'}, msg='参数错误,格式 域名/shareAPI/cutimg/url= ')
        data['url'] = "https://cryptostresser.com/backend/captcha?csrf=462108ed641454d7f152304bbc802520"
        try:
            pic = requests.get(data['url'])
            with open(os.path.join(MEDIA_ROOT,'yanzhengma','1.jpg'), 'wb') as fp:
                fp.write(pic.content)
                fp.close()
            print("下载成功")
        except Exception as e:
            APIResponse(data={'result': '下载失败'}, msg='加载失败')

        try:
            img = cv2.imread(os.path.join(MEDIA_ROOT,'yanzhengma','1.jpg'))

            # 获取高宽
            height = img.shape[0]
            width = img.shape[1]
            # 裁剪 ,顺序是
            """  a: 左上角距离顶部
                 b: 左下角距离顶部
                 c: 左上角距离左边距离
                 d: 右上角距离左边距离"""
            cut_img = img[0: height, 119: width - 119]
            print(type(img))
            print(type(cut_img))


            def cv2_base64(image):
                base64_str = cv2.imencode('.jpg', image)[1].tostring()
                print(base64_str)
                import base64
                base64_str = base64.b64encode(base64_str)
                print(22222222222222222)
                print(base64_str)
                return base64_str
            base64_str = cv2_base64(cut_img)

        except Exception as e:
            APIResponse(data={'result': '下载失败'}, msg='加载失败')

        return APIResponse(data={'result': f'{base64_str}'}, msg='成功')